/*
========================================================================
 Name        : GameZoneAppUi.cpp
 Author      : shitou
 Copyright   : Your copyright notice
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <eikmenub.h>
#include <akncontext.h>
#include <akntitle.h>
#include <GameZone.rsg>
// ]]] end generated region [Generated System Includes]

// [[[ begin generated region: do not modify [Generated User Includes]
#include "GameZoneAppUi.h"
#include "GameZone.hrh"
#include "ThemeListBox.hrh"
#include "GameZoneInitContainerView.h"
#include "ThemeListBoxView.h"
#include "SelectMobileTypeListBoxView.h"
#include "DetailContainerView.h"
// ]]] end generated region [Generated User Includes]
#include <StringLoader.h>
#include <AknQueryDialog.h>
#include <eikapp.h>
#include <AknNoteWrappers.h>
#include <APGCLI.H>
#include "StringUtil.h"
 #include<EikDll.h>

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

_LIT8(KMimeType, "text/plain");
_LIT(KHttpPrefix, "http://");
_LIT8(KHttpPrefix8, "http://");
_LIT(KiniDicFileName,"c:\\private\\e340551d\\GameZone.ini" );

//不扣费，默认是扣费
#define _NOPAY_

//http://218.16.118.166:8082
_LIT(KGetThemeListAddress16,"http://218.16.118.166:8082/newmobile/GetThemeListServlet?id=");
//_LIT(KGetThemeListAddress16,"http://51soji.gicp.net:8082/newmobile/GetThemeListServlet?id=");
#ifdef _NOPAY_
    _LIT8(KGetThemeListAddress,"http://218.16.118.166:8082/newmobile/GetThemeNoPayServlet?imei=");
#else
    _LIT8(KGetThemeListAddress,"http://218.16.118.166:8082/newmobile/GetThemeServlet?imei=");
#endif
//_LIT8(KGetThemeListAddress,"http://51soji.gicp.net:8082/newmobile/GetThemeServlet?imei=");
_LIT(KDownLoadThemeAddress,"http://218.16.118.166:8082/newmobile/ThemeDownloadServlet?imei=");

/**
 * Construct the CGameZoneAppUi instance
 */ 
CGameZoneAppUi::CGameZoneAppUi()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
    iClientEngine = NULL;
    iIap = 0;
    iHeart=NULL;
    iJsonObj = NULL;
    iMobileTypeJson = NULL;
    iMobileType = NULL;
    iImei = NULL;
    iHasGetJsonData = EFalse;
    iGetJsonDataCount = 0;
    iHasSendMessage = EFalse;
    iMobilerTypeName = NULL;
    iImageHost = NULL;
    iTotalPage = 0;
    iCurPage = 0;
    iCurThemeType = NULL;
    iCurThemeItem = NULL;
    iCbaImage = NULL;
    iTitleImage = NULL;
    iInfoImage = NULL;
    iHasSelectedType = ETrue;
    iHasGetListData = EFalse;
	}

/** 
 * The appui's destructor removes the container from the control
 * stack and destroys it.
 */
CGameZoneAppUi::~CGameZoneAppUi()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
    if (iHeart && iHeart->IsActive())
        iHeart->Cancel();
    delete iHeart;
    iHeart=NULL;
    if (iClientEngine && iClientEngine->IsRunning())
    {
        iClientEngine->CancelTransaction();
    }
    delete iClientEngine;
    iClientEngine = NULL;
    delete iImei;
    iImei = NULL;
    if (iJsonObj)
    {
        iJsonObj->Destroy();
        delete iJsonObj;
        iJsonObj = NULL;
    }
    delete iMobileType;
    iMobileType = NULL;
    if (iMobileTypeJson)
    {
        iMobileTypeJson->Destroy();
        delete iMobileTypeJson;
        iMobileTypeJson = NULL;
    }
    iThemeType.ResetAndDestroy();
    iThemeListItem.ResetAndDestroy();
    delete iMobilerTypeName;
    iMobilerTypeName = NULL;
    delete iImageHost;
    iImageHost = NULL;
    
    delete iCbaImage;
    iCbaImage = NULL;
    delete iTitleImage;
    iTitleImage = NULL;
    delete iInfoImage;
    iInfoImage = NULL;
    
    CFileUtil::LogToFileL("=============end====================\r\n");
	}

// [[[ begin generated function: do not modify
void CGameZoneAppUi::InitializeContainersL()
	{
	iGameZoneInitContainerView = CGameZoneInitContainerView::NewL();
	AddViewL( iGameZoneInitContainerView );
	iThemeListBoxView = CThemeListBoxView::NewL();
	AddViewL( iThemeListBoxView );
	iSelectMobileTypeListBoxView = CSelectMobileTypeListBoxView::NewL();
	AddViewL( iSelectMobileTypeListBoxView );
	iDetailContainerView = CDetailContainerView::NewL();
	AddViewL( iDetailContainerView );
	if (iMobilerTypeName && iMobilerTypeName->Length() > 0)
	{
	    iHasSelectedType = ETrue;
	    SetDefaultViewL( *iGameZoneInitContainerView );
	}
	else
        {
        SelectMobileType(1);
        iHasSelectedType = EFalse;
        SetDefaultViewL( *iSelectMobileTypeListBoxView );
        }
	}
// ]]] end generated function

/**
 * Handle a command for this appui (override)
 * @param aCommand command id to be handled
 */
void CGameZoneAppUi::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{ // code to dispatch to the AppUi's menu and CBA commands is generated here
		default:
			break;
		}
	
		
     if ( !commandHandled ) 
          {
          if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )
              {
                  CAknQueryDialog* dlg;
                  dlg = CAknQueryDialog::NewL( CAknQueryDialog::ENoTone );
                  dlg->PrepareLC( R_RESOURCE_QUERY_EXIT_DIALOG ); //锟斤拷锟斤拷源锟侥硷拷锟斤拷锟斤拷曰锟斤拷锟斤拷锟皆达拷锟斤拷锟斤拷锟侥讹拷锟斤拷
                  TInt ret = dlg->RunLD();   //锟斤拷锟矫伙拷选锟斤拷锟角★拷锟斤拷锟斤拷锟截凤拷0锟斤拷选锟今“否”ｏ拷锟津返伙拷0
                  if (ret)
                  {
                      SaveSetting();
                      Exit();
                  }
              }
          }
	// ]]] end generated region [Generated Code]
//	   if ( !commandHandled ) 
//	        {
//	        if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )
//	            {
//	                CAknQueryDialog* dlg;
//	                dlg = CAknQueryDialog::NewL( CAknQueryDialog::ENoTone );
//	                dlg->PrepareLC( R_RESOURCE_QUERY_EXIT_DIALOG ); //锟斤拷锟斤拷源锟侥硷拷锟斤拷锟斤拷曰锟斤拷锟斤拷锟皆达拷锟斤拷锟斤拷锟侥讹拷锟斤拷
//	                TInt ret = dlg->RunLD();   //锟斤拷锟矫伙拷选锟斤拷锟角★拷锟斤拷锟斤拷锟截凤拷0锟斤拷选锟今“否”ｏ拷锟津返伙拷0
//	                if (ret)
//	                {
//	                    SaveSetting();
//	                    Exit();
//	                }
//	            }
//	        }
	}

/** 
 * Override of the HandleResourceChangeL virtual function
 */
void CGameZoneAppUi::HandleResourceChangeL( TInt aType )
	{
	CAknViewAppUi::HandleResourceChangeL( aType );
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}
				
/** 
 * Override of the HandleKeyEventL virtual function
 * @return EKeyWasConsumed if event was handled, EKeyWasNotConsumed if not
 * @param aKeyEvent 
 * @param aType 
 */
TKeyResponse CGameZoneAppUi::HandleKeyEventL(
		const TKeyEvent& aKeyEvent,
		TEventCode aType )
	{
	// The inherited HandleKeyEventL is private and cannot be called
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	return EKeyWasNotConsumed;
	}

/** 
 * Override of the HandleViewDeactivation virtual function
 *
 * @param aViewIdToBeDeactivated 
 * @param aNewlyActivatedViewId 
 */
void CGameZoneAppUi::HandleViewDeactivation( 
		const TVwsViewId& aViewIdToBeDeactivated, 
		const TVwsViewId& aNewlyActivatedViewId )
	{
	CAknViewAppUi::HandleViewDeactivation( 
			aViewIdToBeDeactivated, 
			aNewlyActivatedViewId );
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}

/**
 * @brief Completes the second phase of Symbian object construction. 
 * Put initialization code that could leave here. 
 */ 
void CGameZoneAppUi::ConstructL()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	BaseConstructL( EAknEnableSkin);// | EAppOrientationPortrait ); 
	CAknAppUiBase::SetOrientationL(EAppUiOrientationPortrait);
	LoadSetting();
	
	InitializeContainersL();
	// ]]] end generated region [Generated Contents]
	CFileUtil::LogToFileL("====================begin====================\r\n");
	iClientEngine = CClientEngine::NewL(this);
	//iClientEngine->SetSelectedIap(iIap);
	iImei = GetImeiL();
	ReadImagesL();
	}

void CGameZoneAppUi::ClientBodyReceived(TInt aError,const TDesC8& aBodyData,TInt aAction)
{
    HideWaitDialog();
    CJsonObject* JsonObj = NULL;
    if (aError == KErrNone)
    {
        switch(aAction)
        {
            case EGetJsonData:
                CFileUtil::LogToFileL("date return===========\r\n");
                CFileUtil::LogToFileL(aBodyData);
                if (aBodyData.Find(_L8("<wml>")) > 0)
                {
                    getJsonDataL();
                }
                else
                {
                    //锟斤拷取要锟斤拷示锟侥碉拷址
                    ResolveResponeL(aBodyData);
                    
#ifndef _NOPAY_
                    //锟斤拷锟斤拷锟斤拷锟斤拷台锟斤拷锟斤拷
                    //pay
                    StartSmsService();
#endif
                }
                break;
            case EGetPageData:
                CFileUtil::LogToFileL(aBodyData);
                CFileUtil::LogToFileL("\r\n");
                if (aBodyData.Find(_L8("<wml>")) > 0)
                {
                    iCurPage--;
                    getPage();
                }
                else
                {
                    JsonObj = CJsonObject::Parse(aBodyData);
                    ParseThemeJson(JsonObj);
                    JsonObj->Destroy();
                    delete JsonObj;
                    JsonObj = NULL;
                    iThemeListBoxView->RefashThemeListBox();
                }
                break;
            case EGetImage:
                break;
            case EGetBigImage:
                if (aBodyData.Find(_L8("<wml>")) > 0)
                {
                    this->ActivateLocalViewL(TUid::Uid(EDetailContainerViewId),TUid::Uid(0),_L8(""));
                }
                else
                {
                    this->ActivateLocalViewL(TUid::Uid(EDetailContainerViewId),TUid::Uid(0),aBodyData);
                }
                break;
            case EGetResponeServer:
                break;
        }
    }
    else
    {
        if (aAction == EGetJsonData)
        {
            //getGameList();
        }
        else
        {
            InformationNoteDialog();
        }
    }
}

void CGameZoneAppUi::getPage(TBool aNext)
{
    HBufC* url = HBufC::New(512);
    url->Des().Append(KGetThemeListAddress16);
    if (iCurThemeType)
        url->Des().Append(iCurThemeType->Id());
    url->Des().Append(_L("&page="));
    if (aNext)
        url->Des().AppendNum(++iCurPage);
    else
        url->Des().AppendNum(--iCurPage);
    url->Des().Append(_L("&type="));
    if (iMobilerTypeName && iMobilerTypeName->Length() > 0)
    {
        url->Des().Append(*iMobilerTypeName);
    }
    else
    {
        url->Des().Append(_L("Nokia_N79"));
    }
    PostRequest(*url,KNullDesC,EGetPageData);
    delete url;
}

void CGameZoneAppUi::ChangeType(CThemeType* aType)
{
    if (iCurThemeType)
        iCurThemeType->SetSelected(EFalse);
    iCurThemeType = aType;
    if (iCurThemeType)
        iCurThemeType->SetSelected(ETrue);
    iCurPage = 0;
    getPage();
}

void CGameZoneAppUi::getDetail(CThemeListItem* aItem)
{
    if (aItem)
    {
        if (iCurThemeItem != aItem)
            iCurThemeItem = aItem;
        if (aItem->Bpic().Length() > 0)//iImageHost && 
        {
            GetRequest(iCurThemeItem->Bpic(),EGetBigImage);
        }
        else
        {
            ActivateLocalViewL(TUid::Uid(EDetailContainerViewId));
        }
    }
}

CClientEngine* CGameZoneAppUi::getClientEngine()
{
    return iClientEngine;
}

void CGameZoneAppUi::PostRequest(const TDesC& aUri,const TDesC& aBody,TInt aAction)
{
    ShowWaitDialog(TCallBack(CancelNetWorkCallback, this));
    if (iClientEngine && iClientEngine->IsRunning())
    {
        iClientEngine->CancelTransaction();
    }
    HBufC8* url = CStringUtil::ConvertFromUnicodeToUtf8L(aUri);
    HBufC8* data = CStringUtil::ConvertFromUnicodeToUtf8L(aBody);
    TRAPD(err, iClientEngine->IssueHTTPPostL(*url,KMimeType,*data,aAction));
    if (err)
    {
        HideWaitDialog();
        delete url;
        delete data;
    }
    delete url;
    delete data;
}

void CGameZoneAppUi::GetRequest(const TDesC& aUri,TInt aAction)
{
    ShowWaitDialog(TCallBack(CancelNetWorkCallback, this));
    if (iClientEngine && iClientEngine->IsRunning())
    {
        iClientEngine->CancelTransaction();
    }
    HBufC8* url = CStringUtil::ConvertFromUnicodeToUtf8L(aUri);
    TRAPD(err, iClientEngine->IssueHTTPGetL(*url,aAction));
    if (err)
    {
        delete url;
        HideWaitDialog();
    }
    delete url;
}

void CGameZoneAppUi::InformationNoteDialog( const TDesC& aString)
{
    CAknInformationNote* iInfoNote = new (ELeave) CAknInformationNote;
    if (aString.Length() > 0)
        iInfoNote->ExecuteLD(aString);
    else
    {
        HBufC* text = StringLoader::LoadLC(R_CONNECTING);
        iInfoNote->ExecuteLD(*text);
        CleanupStack::PopAndDestroy(text);
    }
}

void CGameZoneAppUi::ShowWaitDialog( TCallBack aCancelWaitDialog,const TDesC& aLabel)
{
    if (iWaitDialog)
    {
        delete iWaitDialog;
        iWaitDialog = NULL;
    }
    iCancelWaitDialog = aCancelWaitDialog;
    iWaitDialog = new (ELeave) CAknWaitDialog(REINTERPRET_CAST(CEikDialog**, &iWaitDialog));
    iWaitDialog->SetCallback(this);
    if (aLabel.Length() > 0)
        iWaitDialog->SetTextL(aLabel);
    else
    {
        HBufC* text = StringLoader::LoadLC(R_CONNECTING);
        iWaitDialog->SetTextL(*text);
        CleanupStack::PopAndDestroy(text);
    }
    iWaitDialog->ExecuteLD(R_WAIT_DIALOG);
}

void CGameZoneAppUi::HideWaitDialog()
{
    if (iWaitDialog)
    {
        iWaitDialog->ProcessFinishedL();
        delete iWaitDialog;
        iWaitDialog = NULL;
    }
}

void CGameZoneAppUi::DialogDismissedL(TInt aButtonId)
{
    if (-1 == aButtonId)
    {
        if (iCancelWaitDialog.iPtr)
            iCancelWaitDialog.CallBack();
    }
}

TInt CGameZoneAppUi::CancelNetWorkCallback(TAny* aThis)
{
    CClientEngine* engine = static_cast<CGameZoneAppUi*> (aThis)->getClientEngine();
    if (engine && engine->IsRunning())
    {
        engine->CancelTransaction();
    }
    return 0;
}

HBufC8* CGameZoneAppUi::GetImei8L()
{
   HBufC* iemi16 = GetImeiL();
    HBufC8* imeibuf = NULL;
    if (iemi16)
    {
        imeibuf = CStringUtil::ConvertFromUnicodeToUtf8L(*iemi16);
        delete iemi16;
    }
    return imeibuf;
}

HBufC* CGameZoneAppUi::GetImeiL()
{
    CGetIMEI* imei=CGetIMEI::NewL();
    HBufC* retImei = NULL;
    if (imei)
    {
        retImei = imei->GetIMEI().AllocL();
        delete imei;
    }
    return retImei;
}

void CGameZoneAppUi::getGameList(const TDesC& aUri)
{
    if (iClientEngine && iClientEngine->IsRunning())
    {
        iClientEngine->CancelTransaction();
    }
    HBufC8* url = CStringUtil::ConvertFromUnicodeToUtf8L(aUri);
    HBufC8* data = HBufC8::NewL(256);
    TRAPD(err, iClientEngine->IssueHTTPPostL(*url,KMimeType,*data,EGetJsonData));
    if (err)
    {
        HideWaitDialog();
        delete url;
        delete data;
    }
    delete url;
}

void CGameZoneAppUi::WriteToIniFileL(TUid iInfo, const TDesC & aValue)
{
    RFs aFs;
    aFs.Connect();
    CleanupClosePushL(aFs);
    CDictionaryStore* iniFile = Application()->OpenIniFileLC(aFs);
    RDictionaryWriteStream stream;
    stream.AssignLC(*iniFile, iInfo); // direct access by
    stream << aValue;
    stream.CommitL();
    iniFile->CommitL();
    CleanupStack::PopAndDestroy(3);//Stream,iniFile,aFs
}

void CGameZoneAppUi::ReadIniFileL(TUid iInfo, TDes & aValue)
{
    RFs aFs;
    aFs.Connect();
    CleanupClosePushL(aFs);
    CDictionaryStore* iniFile = Application()->OpenIniFileLC(aFs);
    if (iniFile->IsPresentL(iInfo))
    {
        RDictionaryReadStream readStream;
        readStream.OpenLC(*iniFile, iInfo); // direct access
        readStream >> aValue;
        CleanupStack::PopAndDestroy();//readStream
    }
    else
    {
        aValue = _L("");
    }
    CleanupStack::PopAndDestroy(2);//iniFile,aFs
}

void CGameZoneAppUi::ResolveResponeL(const TDesC8& aText)
{
    if (iHeart && iHeart->IsActive())
        iHeart->Cancel();
    CJsonObject* RespJsonObj = CJsonObject::Parse(aText);
    if (RespJsonObj)
    {  
        CJsonObject* urlObj = RespJsonObj->GetObject(_L8("imgurl"));
        if (urlObj)
        {
            iImageHost = urlObj->GetStringFromGbk();
            DEL(urlObj);
        }

        ParseThemeTypeJson(RespJsonObj);
        
        iJsonObj = CJsonObject::NewObject();
        urlObj = RespJsonObj->GetObject(_L8("port"));
        if (urlObj)
        {
            urlObj->Clone();
            iJsonObj->AddObject(_L8("port"),urlObj);
            delete urlObj;
            urlObj = NULL;
        }
        urlObj = RespJsonObj->GetObject(_L8("command"));
        if (urlObj)
        {
            urlObj->Clone();
            iJsonObj->AddObject(_L8("command"),urlObj);
            delete urlObj;
            urlObj = NULL;
        }
        urlObj = RespJsonObj->GetObject(_L8("pb"));
        if (urlObj)
        {
            urlObj->Clone();
            iJsonObj->AddObject(_L8("pb"),urlObj);
            delete urlObj;
            urlObj = NULL;
        }
        //TODO 锟斤拷咏锟斤拷锟斤拷,imei锟斤拷json
        CJsonObject* iapObj = CJsonObject::NewIntObject(getIap());
        iJsonObj->AddObject(_L8("iap"),iapObj);
        delete iapObj;
        iapObj = NULL;
        if (iImei)
        {
            CJsonObject* iemiObj = CJsonObject::NewStringObject(*iImei);
            iJsonObj->AddObject(_L8("imei"),iemiObj);
            delete iemiObj;
            iemiObj = NULL;
        }
        
        RespJsonObj->Destroy();
        delete RespJsonObj;
        RespJsonObj = NULL;
        
        ActivateLocalViewL(TUid::Uid(EThemeListBoxViewId));
    }
    else
    {
        InformationNoteDialog(_L("JSON\u6570\u636E\u683C\u5F0F\u9519\u8BEF"));
    }
}

void CGameZoneAppUi::ParseThemeTypeJson(CJsonObject* aObj)
{
    CJsonObject* lbArrayObj = NULL;
    CJsonObject* lbObj = NULL;
    CJsonObject* ValueObj = NULL;
    CJsonObject* themeArrayObj = NULL;
    HBufC* strBuf = NULL;
    lbArrayObj = aObj->GetObject(_L8("lb"));
    if (lbArrayObj)
    {
        for(TInt i = iThemeType.Count() - 1; i > 0; i--)
        {
            CThemeType* item = iThemeType[i];
            iThemeType.Remove(i);
            delete item;
            item = NULL;
        }
        iThemeType.Reset();
        TInt len = lbArrayObj->GetArrayLength();
        CThemeType* type = NULL;
        for (TInt i = 0; i < len; i++)
        {
            type = new CThemeType();
            lbObj = lbArrayObj->GetArrayById(i);
            ValueObj = lbObj->GetObject(_L8("id"));
            if (ValueObj)
            {
                strBuf = ValueObj->GetStringFromGbk();
                if (strBuf)
                    type->SetIdL(*strBuf);
                DEL(strBuf);
                DEL(ValueObj);
            }
            ValueObj = lbObj->GetObject(_L8("name"));
            if (ValueObj)
            {
                strBuf = ValueObj->GetStringFromGbk();
                if (strBuf)
                    type->SetNameL(*strBuf);
                DEL(strBuf);
                DEL(ValueObj);
            }
            ValueObj = lbObj->GetObject(_L8("totalpage"));
            if (ValueObj)
            {
                iTotalPage = ValueObj->GetInt();
                iCurPage = 1;
                type->SetSelected(ETrue);
                iCurThemeType = type;
                DEL(ValueObj);
            }
            
            themeArrayObj = lbObj->GetObject(_L8("theme"));
            if (themeArrayObj)
                ParseThemeItemJson(themeArrayObj);
            DEL(themeArrayObj);
            DEL(lbObj);

            iThemeType.AppendL(type);
        }
        DEL(lbArrayObj);
    }
}

void CGameZoneAppUi::ParseThemeJson(CJsonObject* aObj)
{
    if (aObj)
    {
        for(TInt i = iThemeListItem.Count() - 1; i > 0; i--)
        {
            CThemeListItem* item = iThemeListItem[i];
            iThemeListItem.Remove(i);
            delete item;
            item = NULL;
        }
        iThemeListItem.Reset();
        CJsonObject* ValueObj = NULL;
        ValueObj = aObj->GetObject(_L8("totalpage"));
        if (ValueObj)
        {
            iTotalPage = ValueObj->GetInt();
            DEL(ValueObj);
        }
        ValueObj = aObj->GetObject(_L8("theme"));
        ParseThemeItemJson(ValueObj);
        DEL(ValueObj);
    }   
}

void CGameZoneAppUi::ParseThemeItemJson(CJsonObject* aObj)
{
    if (aObj)
    {
        TInt count = 0;
        CThemeListItem* item = NULL;
        CJsonObject* ValueObj = NULL;
        CJsonObject* themeObj = NULL;
        HBufC* strBuf = NULL;
        if (aObj)
        {
            count = aObj->GetArrayLength();
            for (TInt j = 0; j < count; j++)
            {
                themeObj = aObj->GetArrayById(j);
                item = new CThemeListItem();
                ValueObj = themeObj->GetObject(_L8("id"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetIdL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("size"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetSizeL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("rq"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetRQL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("xz"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetXZL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("name"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetNameL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("lpic"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetLpicL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("bpic"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetBpicL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("intro"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetIntroL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                ValueObj = themeObj->GetObject(_L8("url"));
                if (ValueObj)
                {
                    strBuf = ValueObj->GetStringFromGbk();
                    if (strBuf)
                        item->SetUrlL(*strBuf);
                    DEL(strBuf);
                    DEL(ValueObj);
                }
                iThemeListItem.AppendL(item);
                DEL(themeObj);
            }
            iHasGetListData = ETrue;
        }
    }
}

void CGameZoneAppUi::LoadSetting()
{
    TFindFile AufFolder(CCoeEnv::Static()->FsSession());
    if (KErrNone == AufFolder.FindByDir(KiniDicFileName, KNullDesC))
    {
        TBuf<32> buf;
        ReadIniFileL(KIapUid, buf);
        TLex lex(buf);
        lex.Val(iIap,EDecimal);
        
        ReadIniFileL(KMobileTypeUid, buf);
        delete iMobilerTypeName;
        iMobilerTypeName = NULL;
        iMobilerTypeName = buf.AllocL();
    }
}

void CGameZoneAppUi::SaveSetting()
{
    TFindFile AufFolder(CCoeEnv::Static()->FsSession());
    if (KErrNone == AufFolder.FindByDir(KiniDicFileName, KNullDesC))
    {
        RFs aFs;
        aFs.Connect();
        CleanupClosePushL(aFs);
        aFs.Delete(KiniDicFileName);
        CleanupStack::PopAndDestroy();//aFs
    }
    TBuf<256> buf;
    buf.Zero();
    if (iClientEngine)
        buf.AppendNum(iClientEngine->SelectedIap(),EDecimal);
    else
        buf.AppendNum(0);  
    WriteToIniFileL(KIapUid, buf);
    
    if (iMobilerTypeName)
        WriteToIniFileL(KMobileTypeUid, *iMobilerTypeName);
}

TUint32 CGameZoneAppUi::getIap()
{
    if (iClientEngine)
        iIap = iClientEngine->SelectedIap();
    return iIap;
}

void CGameZoneAppUi::getJsonDataL()
{
    CFileUtil::LogToFileL("begin getJsonDataL===========\r\n");
    if (iClientEngine && iClientEngine->IsRunning())
    {
        iClientEngine->CancelTransaction();
    }
    HBufC8* url = HBufC8::New(512);
    url->Des().Append(KGetThemeListAddress);
    if (iImei)
        url->Des().Append(*iImei);
    url->Des().Append(_L("&type="));
    if (iMobilerTypeName && iMobilerTypeName->Length() > 0)
    {
        url->Des().Append(*iMobilerTypeName);
    }
    else
    {
        delete iMobilerTypeName;
        iMobilerTypeName = NULL;
        iMobilerTypeName = _L("Nokia_N79").AllocL();
        url->Des().Append(_L("Nokia_N79"));
    }
    TBool ret = iClientEngine->IssueHTTPPostL(*url,KMimeType,_L8(""),EGetJsonData);
    delete url;
    iGetJsonDataCount++;
    CFileUtil::LogToFileL("end IssueHTTPPostL===========\r\n");
    if (!ret)
    	Exit();
}

void CGameZoneAppUi::StartSmsService()
{
    CFileUtil::LogToFileL("begin StartSmsService===========\r\n");
    TBool running = AppIsRun(KIpcProPropertyUid);
    if (!running) //锟叫讹拷锟斤拷锟斤拷锟角凤拷锟斤拷锟斤拷锟斤拷锟斤拷
    {
        TThreadId app_threadid;
        CApaCommandLine* cmdLine;
        cmdLine = CApaCommandLine::NewLC();
        cmdLine->SetExecutableNameL(_L("smsService.exe"));
        cmdLine->SetCommandL(EApaCommandRun);
        RApaLsSession ls;
        User::LeaveIfError(ls.Connect());
        ls.StartApp(*cmdLine, app_threadid);
        ls.Close();
        CleanupStack::PopAndDestroy(); // cmdLine
        //锟斤拷锟斤拷锟斤拷锟斤拷锟絪msService.exe锟斤拷锟斤拷锟襟，斤拷锟斤拷锟斤拷锟斤拷锟节存，锟斤拷锟斤拷息
        StartTimerL(1);
        CFileUtil::LogToFileL("StartSmsService===========\r\n");
    }
    else
    {
        ShareMemAndSendMessage();
    }
    CFileUtil::LogToFileL("end StartSmsService===========\r\n");
}

void CGameZoneAppUi::ShareMemAndSendMessage()
{
    if (iHasSendMessage)
        return ;

    CFileUtil::LogToFileL("ShareMemAndSendMessage===========\r\n");
    int err;
    err=iChk.OpenGlobal(KShareAddr,0);
    if(err!=KErrNone)
    {
        iChk.CreateGlobal(KShareAddr, 0x1000, 0x5000);
    }
    iHasSendMessage = ETrue;
    //取锟矫癸拷锟斤拷锟节达拷锟街�
    TUint8* uid = iChk.Base();
    unsigned int length;

    HBufC8* buf = iJsonObj->ToString();
    if (buf && buf->Length() > 0)
    {
        length = buf->Length();
        Mem::Copy(uid, &length, 4);
        uid += 4;
        Mem::Copy(uid,(TAny *)buf->Des().Ptr(),buf->Length());
        //锟节斤拷锟斤拷锟斤拷锟斤拷锟酵拷诺锟街�
        RProperty::Set(KIpcProPropertyUid, EIntProperty, 0);
    }
    else
    {
        delete buf;
        buf = NULL;
    }
    CFileUtil::LogToFileL("end ShareMemAndSendMessage===========\r\n");
}

void CGameZoneAppUi::Beat()
{
    if (iBeatType == 0)
    {
        if (!iHasGetJsonData)
        {
            getJsonDataL();
            iHasGetJsonData = ETrue;
        }
        else
        {
            iCounter++;
            if (iCounter > 100)
            {
                if (iHeart && iHeart->IsActive())
                    iHeart->Cancel();
                
                CAknQueryDialog* dlg;
                dlg = CAknQueryDialog::NewL( CAknQueryDialog::ENoTone );
                dlg->PrepareLC( R_RESOURCE_TIMEOUT_QUERY_DIALOG ); //锟斤拷锟斤拷源锟侥硷拷锟斤拷锟斤拷曰锟斤拷锟斤拷锟皆达拷锟斤拷锟斤拷锟侥讹拷锟斤拷
                TInt ret = dlg->RunLD();   //锟斤拷锟矫伙拷选锟斤拷锟角★拷锟斤拷锟斤拷锟截凤拷0锟斤拷选锟今“否”ｏ拷锟津返伙拷0
                if (ret)
                {
                    SaveSetting();
                    Exit();
                }
                else
                {
//                    if (iGetJsonDataCount > 3)
//                    {
//                        iClientEngine->SetSelectedIap(0);
//                        iGetJsonDataCount = 0;
//                    }
                  getJsonDataL();
                  iCounter = 0;
                  iHeart->Start(ETwelveOClock,this);
                }
            }
        }
    }
    else if (iBeatType == 1)
    {
        TBool running = AppIsRun(KIpcProPropertyUid);
        if (running)
        {
            ShareMemAndSendMessage();
            if (iHeart && iHeart->IsActive())
                iHeart->Cancel();
            delete iHeart;iHasSendMessage = ETrue;
            iHeart=NULL;
        }
    }
}

void CGameZoneAppUi::Synchronize()
    {
    }

void CGameZoneAppUi::StartTimerL(TInt aType)
    {
    iBeatType = aType;
    if (!iHeart)
    {
        iHeart=CHeartbeat::NewL(0); // neutral priority
    }
    if (iHeart->IsActive())
    {
        iHeart->Cancel();
    }
    iHeart->Start(ETwelveOClock,this); // 1 second intervals
    iCounter = 0;
    }

bool CGameZoneAppUi::AppIsRun(TUid appuid)//锟叫讹拷应锟矫筹拷锟斤拷锟角凤拷锟斤拷锟斤拷锟斤拷锟斤拷
{
    bool ret = false;
    TFullName name( KNullDesC() ); 
    TFindProcess find; 
    while ( KErrNotFound != find.Next( name ) ) 
    { 
      if ( KErrNotFound != name.FindF( _L("smsService.exe") ) ) 
      { 
          ret = true;
          break;
      } 
    } 
    return ret;
}

RPointerArray<CThemeType> CGameZoneAppUi::ThemeType()
{
    return iThemeType;
}

RPointerArray<CThemeListItem> CGameZoneAppUi::ThemeListItem()
{
    return iThemeListItem;
}

CMobileType* CGameZoneAppUi::MobileType()
{
    return iMobileType;
}

CThemeListItem* CGameZoneAppUi::CurThemeItem()
{
    return iCurThemeItem;
}

CThemeType* CGameZoneAppUi::CurThemeType()
{
    return iCurThemeType;
}

void CGameZoneAppUi::SelectMobileType(TInt aIsBegin)
{
    if (!iMobileType)
    {
        iMobileType = new CMobileType();
    }
    if (!iMobileTypeJson)
    {
        TFileName filename = getImageFileName(_L("\\resource\\apps\\MobileType.txt"));
        HBufC8* file = CStringUtil::ConvertFromUnicodeToUtf8L(filename);
        iMobileTypeJson = CJsonObject::NewObjectFromFile(*file);//锟街伙拷锟酵猴拷
        delete file;
        file = NULL;
    }
    iMobileType->setJsonData(iMobileTypeJson);
    if (!aIsBegin)
        ActivateLocalViewL(TUid::Uid(ESelectMobileTypeListBoxViewId));
}

const TDesC& CGameZoneAppUi::MobilerTypeName()
{
    if (iMobilerTypeName)
        return *iMobilerTypeName;
    return KNullDesC;
}

void CGameZoneAppUi::setMobilerTypeNameL(const TDesC& aTypeName)
{
    delete iMobilerTypeName;
    iMobilerTypeName = NULL;
    iMobilerTypeName = aTypeName.AllocL();
    
    delete iMobileType;
    iMobileType = NULL;
    if (iMobileTypeJson)
    {
        iMobileTypeJson->Destroy();
        delete iMobileTypeJson;
        iMobileTypeJson = NULL;
    }
    
    if (!iHasSelectedType)
    {
        iHasSelectedType = ETrue;
        ActivateLocalViewL(TUid::Uid(EGameZoneInitContainerViewId));
    }
    else
        ActivateLocalViewL(TUid::Uid(EThemeListBoxViewId));
}

TBool CGameZoneAppUi::HasPrePage()
{
    if (iCurPage > 1)
        return ETrue;
    return EFalse;
}

TBool CGameZoneAppUi::HasNextPage()
{
    if (iCurPage < iTotalPage)
        return ETrue;
    return EFalse;
}

void CGameZoneAppUi::OpenUrlL(const TDesC& aUrl)
{
    if(aUrl.Length() <= 0)
        return;
    const TInt KBrowserUid1 = 0x1020724D;
    const TInt KBrowserUid2 = 0x10008D39;
    RApaLsSession appArcSession;
    User::LeaveIfError(appArcSession.Connect()); // connect to AppArc server
    HBufC* param = HBufC::NewLC( aUrl.Length() + 8 );
    param->Des().Format( _L( "4 %S" ),&aUrl );
    // Wap Browser's constants UId
    TUid browserId( TUid::Uid( KBrowserUid1 ) );
    TApaAppInfo appInfo;
    if( appArcSession.GetAppInfo( appInfo, browserId ) != KErrNone )
        {
        browserId = TUid::Uid( KBrowserUid2 );
        }
    TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
    TApaTask task = taskList.FindApp( browserId );
    if ( task.Exists() )
        {
        HBufC8* param8 = HBufC8::NewLC( param->Length() * 4 );
        param8->Des().Append( *param );
        task.SendMessage( TUid::Uid( 0 ), *param8 ); // Uid is not used
        CleanupStack::PopAndDestroy(); // param8
        }
    else
        {
        TThreadId id;
        appArcSession.StartDocument( *param, browserId, id );
        }
    appArcSession.Close();
    CleanupStack::PopAndDestroy(); // param
    return; 
}

void CGameZoneAppUi::DownLoadCurTheme()
{
    if (iCurThemeItem)
    {
        HBufC* url = HBufC::New(512);
        url->Des().Append(KDownLoadThemeAddress);
        if (iImei)
            url->Des().Append(*iImei);
        url->Des().Append(_L("&id="));
        url->Des().Append(iCurThemeItem->Id());
        OpenUrlL(*url);
        delete url;
        url = NULL;
    }
}

TFileName CGameZoneAppUi::getImageFileName(const TDesC& aPath)
{
    iImageFileName.Zero();
    TBuf<3> buf;
#ifdef __WINSCW__
    buf.Copy(_L("c:"));
#else
    TFileName full_fname;
    full_fname =this->Application()->AppFullName();
    TParse parse;
    parse.Set(full_fname,NULL,NULL);
    buf.Copy(parse.Drive());
#endif
    iImageFileName.Append(buf);
    iImageFileName.Append(aPath);
    return iImageFileName;
}
    
const TDesC& CGameZoneAppUi::getImageHost()
{
    if (iImageHost)
        return *iImageHost;
    return KNullDesC;
}

void CGameZoneAppUi::setHasGetListData(TBool aValue)
{
	iHasGetListData = aValue;
}

TBool CGameZoneAppUi::HasGetListData()
{
	return iHasGetListData;
}

void CGameZoneAppUi::ReadImagesL()
{
    iCbaImage = new CImage();
    iCbaImage->ReadImageFromFileL(getImageFileName(_L("\\resource\\apps\\cba.png")));
    iTitleImage = new CImage();
    iTitleImage->ReadImageFromFileL(getImageFileName(_L("\\resource\\apps\\title.png")));
    iInfoImage = new CImage();
    iInfoImage->ReadImageFromFileL(getImageFileName(_L("\\resource\\apps\\info.png")));
}
